<template>
  <div class="container">
    <div class="search-container">
      <el-form :inline="true" :model="searchForm" ref="searchFormRef">
        <el-form-item label="入场日期">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="handleDateRangeChange"
          />
        </el-form-item>
        <el-form-item label="耳标号">
          <el-select v-model="searchForm.earNumber" placeholder="请选择耳标号" clearable filterable style="width: 160px">
            <el-option 
              v-for="item in earNumberList" 
              :key="item.Id" 
              :label="item.Name" 
              :value="item.Id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="负责人">
          <el-select v-model="searchForm.principal" placeholder="请选择负责人" clearable filterable style="width: 160px">
            <el-option v-for="item in responsiblePersonOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="table-container">
      <div class="table-header">
        <div class="operations" style="margin-left: 0;">
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </div>
      </div>

      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        border
        @selection-change="handleSelectionChange"
        :max-height="600"
        @sort-change="handleSortChange"
      >
        <template #empty>
          <div class="no-data">
            <el-icon><Document /></el-icon>
            <p>{{ emptyDataMessage }}</p>
            <div v-if="noDataReason === 'no_records'" class="action-buttons">
              <el-button type="primary" @click="handleAdd">添加第一条记录</el-button>
            </div>
          </div>
        </template>
        
        <el-table-column label="序号" width="60" align="center" fixed="left">
          <template #default="scope">{{ scope.$index + 1 + (currentPage - 1) * pageSize }}</template>
        </el-table-column>
        <el-table-column prop="BreedingDate" label="配种日期" width="120" align="center" sortable="custom">
          <template #default="scope">{{ formatDate(scope.row.BreedingDate) }}</template>
        </el-table-column>
        <el-table-column prop="LastBreedingDate" label="上胎配种日期" width="120" align="center">
          <template #default="scope">{{ formatDate(scope.row.LastBreedingDate) }}</template>
        </el-table-column>
        <el-table-column prop="EarNumber" label="耳号" width="100" align="center" sortable="custom">
          <template #default="scope">{{ formatEarNumber(scope.row.EarNumber) }}</template>
        </el-table-column>
        <el-table-column prop="FemaleBreed" label="种母品种" width="100" align="center" />
        <el-table-column prop="FirstMaleSheep" label="首配公羊" width="100" align="center" />
        <el-table-column prop="ExtraMaleSheep" label="补配公羊" width="100" align="center" />
        <el-table-column prop="BreedingMethod" label="配种方式" width="100" align="center" />
        <el-table-column prop="FemaleEstrusType" label="种母发情类型" width="120" align="center" />
        <el-table-column prop="FirstBreedingScore" label="首配评分" width="100" align="center" sortable="custom" />
        <el-table-column prop="BreedingScore" label="配种评分" width="100" align="center" sortable="custom" />
        <el-table-column prop="BreedingHouse" label="当前栋舍" width="100" align="center">
          <template #default="scope">{{ formatBuilding(scope.row.BreedingHouse) }}</template>
        </el-table-column>
        <el-table-column prop="BreedingPen" label="当前栏位" width="100" align="center">
          <template #default="scope">{{ formatPen(scope.row.BreedingPen) }}</template>
        </el-table-column>
        <el-table-column prop="TransferHouse" label="转入栋舍" width="100" align="center">
          <template #default="scope">{{ formatBuilding(scope.row.TransferHouse) }}</template>
        </el-table-column>
        <el-table-column prop="BreedingStatus" label="繁殖状态" width="100" align="center" sortable="custom" />
        <el-table-column prop="EventDate" label="事件日期" width="120" align="center">
          <template #default="scope">{{ formatDate(scope.row.EventDate) }}</template>
        </el-table-column>
        <el-table-column prop="Principal" label="负责人" width="100" align="center" sortable="custom" />
        <el-table-column prop="Remark" label="备注" min-width="120" align="center" />
        <el-table-column prop="Creator" label="创建人" width="100" align="center" />
        <el-table-column prop="CreateTime" label="创建时间" width="150" align="center" sortable="custom">
          <template #default="scope">{{ formatDateTime(scope.row.CreateTime) }}</template>
        </el-table-column>
        <el-table-column prop="DocumentNo" label="单据号" width="140" align="center" />
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model-current-page="currentPage"
          v-model-page-size="pageSize"
          :page-sizes="[10, 20, 30, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
        />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getEweMatingList, deleteEweMating, getEweMatingOwning, getEweMatingListByGet } from '../../utils/requestEweMating'
import { useRouter } from 'vue-router'
import { Document, Refresh } from '@element-plus/icons-vue'
import { serviceRead, Sheep_BreedingRead } from '../../utils/Interceptors'

const router = useRouter()

// 添加耳号列表、栋舍列表和栏位列表
const earNumberList = ref<any[]>([])
const earNumberMap = ref<Record<string, string>>({})  // 用于ID到名称的映射
const buildingList = ref<any[]>([])
const buildingMap = ref<Record<string, string>>({})   // 栋舍ID到名称的映射
const penList = ref<any[]>([])
const penMap = ref<Record<string, string>>({})        // 栏位ID到名称的映射

// 格式化耳号显示
const formatEarNumber = (earId: string): string => {
  if (!earId) return '';
  return earNumberMap.value[earId] || earId;
}

// 格式化栋舍显示
const formatBuilding = (buildingId: string): string => {
  if (!buildingId) return '';
  return buildingMap.value[buildingId] || buildingId;
}

// 格式化栏位显示
const formatPen = (penId: string): string => {
  if (!penId) return '';
  return penMap.value[penId] || penId;
}

// 日期时间格式化函数
const formatDateTime = (dateStr: string | null | undefined): string => {
  // 处理空值或无效值
  if (!dateStr || dateStr === 'null' || dateStr === 'undefined' || dateStr.includes('DBNull')) {
    return '';
  }
  
  try {
    const date = new Date(dateStr);
    if (isNaN(date.getTime())) return '';
    
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
  } catch {
    // 发生错误时返回空字符串
    console.warn('日期格式化错误:', dateStr);
    return '';
  }
}

// 仅日期格式化函数
const formatDate = (dateStr: string | null | undefined): string => {
  // 处理空值或无效值
  if (!dateStr || dateStr === 'null' || dateStr === 'undefined' || dateStr.includes('DBNull')) {
    return '';
  }
  
  try {
    const date = new Date(dateStr);
    if (isNaN(date.getTime())) return '';
    
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
  } catch {
    // 发生错误时返回空字符串
    console.warn('日期格式化错误:', dateStr);
    return '';
  }
}

// 搜索表单
const searchForm = reactive({
  earNumber: '',
  principal: '',
  breedingDateStart: null as string | null,
  breedingDateEnd: null as string | null,
  pageIndex: 1,
  pageSize: 10,
  sortField: 'BreedingDate',
  sortOrder: 'desc' as 'asc' | 'desc'
})

// 日期范围选择器
const dateRange = ref<[string, string] | null>(null)
const handleDateRangeChange = (val: [string, string] | null) => {
  // 确保即使日期为null，也将其设置为空字符串而不是null
  searchForm.breedingDateStart = val ? val[0] : "";
  searchForm.breedingDateEnd = val ? val[1] : "";
}

// 表格数据
const tableData = ref<any[]>([])
const loading = ref(false)
const selectedRows = ref<any[]>([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchFormRef = ref()

// 添加表格空状态的提示信息
const emptyDataMessage = ref('暂无数据');
const noDataReason = ref(''); // 'no_records', 'search_no_match', 'error'

// 获取用户列表
const responsiblePersonOptions = ref<{label: string, value: string}[]>([])

// 获取列表数据
const fetchData = async () => {
  loading.value = true;
  try {
    const requestParams = {
      pageIndex: currentPage.value, // 注意这里直接用当前页码
      pageSize: pageSize.value,
      breedingDateStart: searchForm.breedingDateStart,
      breedingDateEnd: searchForm.breedingDateEnd,
      earNumber: searchForm.earNumber.trim() || "",
      principal: searchForm.principal.trim() || "",
      sortField: searchForm.sortField || "BreedingDate",
      sortOrder: searchForm.sortOrder || "desc"
    };
    const res = await getEweMatingList(requestParams);
    processApiResponse(res);
  } catch (error) {
    emptyDataMessage.value = '获取数据失败，请稍后再试';
    noDataReason.value = 'error';
    ElMessage.error('获取数据失败，请检查网络连接');
    tableData.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
}

// 处理API响应数据
const processApiResponse = (res: any) => {
  if (res && res.data) {
    const apiData = res.data;
    if (apiData.code === 200 && apiData.data && Array.isArray(apiData.data.PageData)) {
      tableData.value = apiData.data.PageData;
      total.value = apiData.data.TotalCount || 0;
      currentPage.value = apiData.data.PageIndex || 1;
      pageSize.value = apiData.data.PageSize || 10;
      noDataReason.value = '';
    } else {
      resetTableData(apiData.msg || '查询失败');
      ElMessage.error(apiData.msg || '查询失败');
    }
  } else {
    resetTableData('接口返回数据为空');
  }
}

// 尝试使用owning接口获取数据
const tryOwningApi = async () => {
  try {
    console.log('尝试使用owning接口...');
    const res = await getEweMatingOwning();
    console.log('owning接口响应:', res);
    
    if (res && res.data && res.data.code === 200) {
      if (Array.isArray(res.data.data) && res.data.data.length > 0) {
        // 处理返回的数组数据
        tableData.value = res.data.data.map(processItem);
        total.value = res.data.data.length;
        console.log(`成功从owning接口获取到 ${total.value} 条记录`);
        ElMessage.success(`成功获取到 ${total.value} 条记录`);
        noDataReason.value = '';
      } else {
        // 数据为空数组
        tableData.value = [];
        total.value = 0;
        emptyDataMessage.value = '系统中暂无种母配种记录，请添加';
        noDataReason.value = 'no_records';
        console.log('owning接口返回空数组');
      }
    } else if (res.data && res.data.msg && res.data.msg.includes('不存在')) {
      // 处理"母羊配种记录不存在"的情况
      tableData.value = [];
      total.value = 0;
      emptyDataMessage.value = '系统中暂无种母配种记录，请点击下方按钮添加';
      noDataReason.value = 'no_records';
      console.log('系统中没有种母配种记录');
    } else {
      const errorMsg = res?.data?.msg || 'owning接口返回格式错误';
      console.error('owning接口返回错误:', errorMsg);
      resetTableData(`owning接口错误: ${errorMsg}`);
      emptyDataMessage.value = '获取数据失败，请稍后再试';
      noDataReason.value = 'error';
      ElMessage.error(errorMsg);
    }
  } catch (error) {
    console.error('owning接口请求失败:', error);
    resetTableData('owning接口请求失败');
    emptyDataMessage.value = '网络请求失败，请检查网络连接';
    noDataReason.value = 'error';
    ElMessage.error('获取数据失败，请稍后再试');
  }
}

// 处理单个数据项，确保没有null或DBNull值
const processItem = (item: Record<string, any>) => {
  const processedItem: Record<string, any> = {};
  
  // 遍历对象的每个属性
  Object.keys(item).forEach(key => {
    const value = item[key];
    
    // 处理null、undefined或包含DBNull的值
    if (value === null || value === undefined) {
      processedItem[key] = '';
    } 
    // 处理日期类型的特殊情况
    else if (typeof value === 'string' && (key.includes('Date') || key.includes('Time'))) {
      if (value.includes('DBNull')) {
        processedItem[key] = '';
      } else {
        processedItem[key] = value;
      }
    } 
    // 处理其他情况
    else {
      processedItem[key] = value;
    }
  });
  
  return processedItem;
}

// 重置表格数据的辅助函数
const resetTableData = (reason: string) => {
  tableData.value = [];
  total.value = 0;
  if (reason.includes('不存在')) {
    emptyDataMessage.value = '系统中暂无种母配种记录，请点击下方按钮添加';
    noDataReason.value = 'no_records';
  } else if (reason.includes('查询')) {
    emptyDataMessage.value = '没有匹配的搜索结果';
    noDataReason.value = 'search_no_match';
  } else {
    emptyDataMessage.value = '暂无数据';
    noDataReason.value = 'error';
  }
  console.warn(`表格数据已重置, 原因: ${reason}`);
}

// 搜索
const handleSearch = () => {
  console.log('执行查询，搜索条件:', {
    earNumber: searchForm.earNumber,
    principal: searchForm.principal,
    breedingDateStart: searchForm.breedingDateStart,
    breedingDateEnd: searchForm.breedingDateEnd,
    sortField: searchForm.sortField,
    sortOrder: searchForm.sortOrder
  });
  
  // 将日期设为null而不是空字符串，因为后端可能需要null来表示不筛选日期
  if (!searchForm.breedingDateStart) searchForm.breedingDateStart = null;
  if (!searchForm.breedingDateEnd) searchForm.breedingDateEnd = null;
  
  // 更新提示信息以反映搜索操作
  emptyDataMessage.value = '没有找到匹配的记录';
  noDataReason.value = 'search_no_match';
  ElMessage.info('正在查询，请稍候...');
  currentPage.value = 1;
  fetchData();
}

// 重置搜索条件
const resetSearch = () => {
  if (searchFormRef.value) {
    searchFormRef.value.resetFields();
  }
  dateRange.value = null;
  // 使用null而不是空字符串
  searchForm.breedingDateStart = null;
  searchForm.breedingDateEnd = null;
  searchForm.earNumber = '';
  searchForm.principal = '';
  searchForm.sortField = 'BreedingDate';
  searchForm.sortOrder = 'desc';
  
  currentPage.value = 1;
  fetchData();
}

// 分页大小变化
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  searchForm.pageSize = val;
  console.log('每页记录数变更为:', val);
  fetchData();
}

// 页码变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  searchForm.pageIndex = val;
  console.log('当前页变更为:', val);
  fetchData();
}

// 表格排序变化
const handleSortChange = (column: any) => {
  if (column.prop && column.order) {
    searchForm.sortField = column.prop;
    searchForm.sortOrder = column.order === 'ascending' ? 'asc' : 'desc';
    console.log('排序变更:', searchForm.sortField, searchForm.sortOrder);
    fetchData();
  }
}

// 多选变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

// 查看详情
const handleView = (row: any) => {
  router.push({
    path: '/EweMating',
    query: { breedingId: row.BreedingId }
  })
}

// 编辑
const handleEdit = (row: any) => {
  router.push({
    path: '/EweMating',
    query: { breedingId: row.BreedingId }
  })
}

// 删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`确认删除种母配种记录 ${row.BreedingId} 吗？`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteEweMating(row.BreedingId);
      
      // 判断API返回状态
      if (res && res.data && res.data.code === 200) {
        ElMessage.success('删除成功');
        fetchData();
      } else {
        ElMessage.error(res?.data?.msg || '删除失败');
      }
    } catch (error) {
      console.error('删除失败', error);
      ElMessage.error('删除失败');
    }
  }).catch(() => {
    // 用户取消删除操作
  });
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条记录');
    return;
  }
  
  ElMessageBox.confirm(`确认删除选中的 ${selectedRows.value.length} 条记录吗？`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const promises = selectedRows.value.map(row => deleteEweMating(row.BreedingId));
      await Promise.all(promises);
      ElMessage.success('批量删除成功');
      fetchData();
    } catch (error) {
      console.error('批量删除失败', error);
      ElMessage.error('批量删除失败');
    }
  }).catch(() => {
    // 用户取消批量删除操作
  });
}

// 新增
const handleAdd = () => {
  router.push('/EweMating')
}

// 刷新数据
const refreshData = () => {
  fetchData()
}

// 获取耳号列表
const fetchEarNumberList = async () => {
  try {
    const res = await Sheep_BreedingRead.get('/api/EliminationInfo/GetSheepFilesIdEarNumber');
    if (res.data && res.data.code === 200 && res.data.data) {
      earNumberList.value = res.data.data;
      // 创建ID到名称的映射
      const map: Record<string, string> = {};
      res.data.data.forEach((item: any) => {
        if (item && item.Id && item.Name) {
          map[item.Id] = item.Name;
        }
      });
      earNumberMap.value = map;
    }
  } catch (error) {
    console.error('获取耳号列表失败:', error);
    ElMessage.error('获取耳号列表失败');
  }
}

// 获取栋舍列表
const fetchBuildingList = async () => {
  try {
    const res = await Sheep_BreedingRead.get('/api/Sheepfarm/SearchBuildingManagement', {
      params: { PageIndex: 1, PageSize: 100 }
    });
    if (res.data && res.data.code === 200 && res.data.PageData) {
      buildingList.value = res.data.PageData;
      // 创建ID到名称的映射
      const map: Record<string, string> = {};
      res.data.PageData.forEach((item: any) => {
        if (item && item.BuildingId && item.House_name) {
          map[item.BuildingId] = item.House_name;
        }
      });
      buildingMap.value = map;
    }
  } catch (error) {
    console.error('获取栋舍列表失败:', error);
    ElMessage.error('获取栋舍列表失败');
  }
}

// 获取栏位列表
const fetchPenList = async () => {
  try {
    const res = await Sheep_BreedingRead.get('/api/EliminationInfo/GetFieldManagementIdName');
    if (res.data && res.data.code === 200 && res.data.data) {
      penList.value = res.data.data;
      // 创建ID到名称的映射
      const map: Record<string, string> = {};
      res.data.data.forEach((item: any) => {
        if (item && item.Id && item.Name) {
          map[item.Id] = item.Name;
        }
      });
      penMap.value = map;
    }
  } catch (error) {
    console.error('获取栏位列表失败:', error);
    ElMessage.error('获取栏位列表失败');
  }
}

onMounted(async () => {
  // 获取用户列表
  try {
    const { data } = await serviceRead.get('/api/User/SraechUser', {
      params: { PageIndex: 1, PageSize: 100 }
    })
    if (data.code === 200 && Array.isArray(data.PageData)) {
      responsiblePersonOptions.value = data.PageData.map((user: any) => ({
        label: user.UserName,
        value: user.UserName
      }))
    } else {
      responsiblePersonOptions.value = []
    }
  } catch (e) {
    responsiblePersonOptions.value = []
    ElMessage.error('获取用户列表失败')
  }
  
  // 获取耳号、栋舍和栏位列表
  await Promise.all([
    fetchEarNumberList(),
    fetchBuildingList(),
    fetchPenList()
  ]);
  
  fetchData()
})
</script>

<style scoped>
.container {
  padding: 20px;
}

.search-container {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.table-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.table-header .title {
  font-size: 18px;
  font-weight: bold;
}

.operations {
  display: flex;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.no-data {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  color: #909399;
}

.no-data .el-icon {
  font-size: 48px;
  margin-bottom: 10px;
}

.action-buttons {
  margin-top: 20px;
}
</style> 